package com.carp.springframework.beans.factory.support;

import com.carp.springframework.beans.BeansException;
import com.carp.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

/**
 * @author lile
 * @date 2023/2/3
 */
public class JDKInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor<?> ctor, Object[] args) {
        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            return Objects.isNull(ctor) ? clazz.getDeclaredConstructor().newInstance() :
                    clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }

    }
}
